package soccerBet.project.mail;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import soccerBet.project.betfair.exchange.BFExchangeServiceStub.BetTypeEnum;
import soccerBet.project.dao.DestinatariosDAO;
import soccerBet.project.objects.Destinatarios;
import soccerBet.project.objects.Precos;
import soccerBet.project.ruleEngine.ApostaRule;
import soccerBet.project.services.ApostaService;
import soccerBet.project.services.DestinatariosService;
import soccerBet.project.utils.Prop;
import soccerBet.project.utils.Utils;
 
public class SendMailTLS {
 
	private String menssagem="";
	private String subject="";
	
	
	public SendMailTLS(Precos preco, ApostaRule rule) {
		
		SimpleDateFormat format = new SimpleDateFormat("dd-MM HH:mm");
		
		ApostaService apostaService = new ApostaService();
		
		this.setSubject("SoccerBet: Aposta Efectuada");
		
		this.menssagem = "Jogo: "+rule.getJogo()+"<br/>"+
    "Tipo de aposta: "+apostaService.getApostaDescricaoBySID(rule.getTipoAposta()).getDescricao()+"<br/>"+
    "Tipo: "+Utils.getTipoAposta(rule.getTipo())+"<br/>"+
		"Odd: "+rule.getPrice()+"<br/>";
		
    this.menssagem += (rule.getTipo() == BetTypeEnum.B) ?  ("Risco: "+rule.getSize()+"<br/>"+ "Ganho: "+(rule.getSize()*rule.getPrice())+"<br/>") : ("Risco: "+(rule.getSize()*rule.getPrice())+"<br/>"+"Ganho: "+rule.getSize()+"<br/>")  +
    "Data: "+format.format(preco.getData());
	}

	
	public SendMailTLS(String erro) {

		this.setSubject("SoccerBet: Erro");
		this.menssagem =erro;
		
	}

	public SendMailTLS(String subject,String msg) {

		this.setSubject(subject);
		this.menssagem =msg;
		
	}
	

	public void enviaEmail(){

		DestinatariosService destinService = new DestinatariosService();
		final String username = (String) Prop.properties.get("soccerBet.email.username");
		final String password = (String) Prop.properties.get("soccerBet.email.password");
		
		//"socc3rB3t@gmail.com";
		//"b8P17zf74YU0VwP";
		
		List<Destinatarios> destiList = destinService.getAllDestinatarios();
		
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");
 

		Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
 
		try {
 
			
			InternetAddress[] addressTo = new InternetAddress[destiList.size()];
	        for (int i = 0; i <destiList.size(); i++)
	        {
	             addressTo[i] = new InternetAddress(destiList.get(i).getEmail());
	        }
			
	        MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress("socc3rB3t@gmail.com"));
			message.setRecipients(Message.RecipientType.BCC,addressTo);
			message.setSubject(this.getSubject());
			message.setText(this.menssagem, "utf-8", "html");
			Transport.send(message);
 
			System.out.println("E-mail Enviado....");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void sendEmailWithAttachment(String fileName){

		DestinatariosService destinService = new DestinatariosService();
		final String username = (String) Prop.properties.get("soccerBet.email.username");
		final String password = (String) Prop.properties.get("soccerBet.email.password");
		
		//"socc3rB3t@gmail.com";
		//"b8P17zf74YU0VwP";
		
		List<Destinatarios> destiList = destinService.getDestinatariosPermissoes();
		
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");
 

		Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
 
		try {
 
			
			InternetAddress[] addressTo = new InternetAddress[destiList.size()];
	        for (int i = 0; i <destiList.size(); i++)
	        {
	             addressTo[i] = new InternetAddress(destiList.get(i).getEmail());
	        }
			
	        MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress("socc3rB3t@gmail.com"));
			message.setRecipients(Message.RecipientType.BCC,addressTo);
			message.setSubject(this.getSubject());
			
            //
            // Set the email message text.
            //
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(this.menssagem, "utf-8", "html");
 
            //
            // Set the email attachment file
            //
            FileDataSource fileDataSource = new FileDataSource(fileName);
 
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(fileDataSource.getName());
 
            //
            // Create Multipart E-Mail.
            //
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagePart);
            multipart.addBodyPart(attachmentPart);
 
            message.setContent(multipart);
			
			
			Transport.send(message);
 
			System.out.println("E-mail Enviado com anexo....");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	
	public void setMenssagem(String menssagem) {
		this.menssagem = menssagem;
	}

	public String getMenssagem() {
		return menssagem;
	}


	public void setSubject(String subject) {
		this.subject = subject;
	}


	public String getSubject() {
		return subject;
	}
}